package top.broncho.mvvm.util

import android.content.Context
import top.broncho.gank.BuildConfig
import top.broncho.gank.constant.Constant
import top.broncho.gank.http.interceptor.HeaderInterceptor
import top.broncho.gank.http.interceptor.SaveCookieInterceptor
import okhttp3.Cache
import okhttp3.CacheControl
import okhttp3.Interceptor
import okhttp3.Interceptor.Companion.invoke
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit


private const val READ_TIMEOUT = 20L//读取超时时间,单位  秒
private const val WRITE_TIMEOUT = 20L//读取超时时间,单位  秒
private const val CONN_TIMEOUT = 10L//连接超时时间,单位  秒

private const val CACHE_DIR = "retrofit_manager_disk_cache"

private fun Context.provideCacheDir(): File {
    return externalCacheDir.takeIf { it != null } ?: cacheDir
}

private fun Context.provideCache(): Cache {
    return Cache(File(provideCacheDir(), CACHE_DIR), 1024 * 1024 * 50)
}

private fun Context.provideOkHttpClient(): OkHttpClient {
    //打印请求log
    val logging = HttpLoggingInterceptor().apply {
        level =
            if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY
            else HttpLoggingInterceptor.Level.NONE
    }
    return OkHttpClient.Builder()
        .addInterceptor(logging)
        .addInterceptor(HeaderInterceptor())
        .addInterceptor(SaveCookieInterceptor())
        .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
        .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
        .connectTimeout(CONN_TIMEOUT, TimeUnit.SECONDS)
        .cache(provideCache())
        //.addInterceptor(logging)
        .build()//初始化一个client,不然retrofit会自己默认添加一个
}

private fun Context.provideOfflineCacheInterceptor(): Interceptor {
    return invoke { chain ->
        var request = chain.request()
        if (!hasInternet()) {
            val offlineCacheTime = 3 //离线的时候的缓存的过期时间
            request = request.newBuilder()
                .cacheControl(
                    CacheControl
                        .Builder()
                        .maxStale(offlineCacheTime, TimeUnit.DAYS)
                        .onlyIfCached()
                        .build()
                )
                .build()
        }
        chain.proceed(request)
    }
}

private fun provideNetCacheInterceptor(): Interceptor {
    return invoke { chain ->
        val request = chain.request()
        val response = chain.proceed(request)
//        val onlineCacheTime = 60 * 60 * 24 //在线的时候的缓存过期时间，如果想要不缓存，直接时间设置为0
        val onlineCacheTime = 5 * 60 //在线的时候的缓存过期时间，如果想要不缓存，直接时间设置为0
        response.newBuilder()
            .removeHeader("Pragma")
            .removeHeader("Cache-Control")
            .header("Cache-Control", "public, max-age=$onlineCacheTime")
            .build()
    }
}

fun Context.provideRetrofit(): Retrofit {
    val client = provideOkHttpClient()
    return Retrofit.Builder().client(client)
        .baseUrl(Constant.BASE_URL)
        .callFactory(CallFactoryProxy(client))
        .addConverterFactory(GsonConverterFactory.create())
        .build()
}
